package com.usian.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.usian.admin.mapper.AdUserMapper;
import com.usian.admin.service.AdUserService;
import com.usian.common.AppJwtUtil;
import com.usian.model.admin.dtos.AdUserDto;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.common.dtos.ResponseResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

@Service
public class AdUserServiceImpl extends BaseServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    @Override
    public ResponseResult login(AdUserDto dto) {
        if (dto == null || StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) {
            return paramError;
        }
        //上面已做非空校验
        LambdaQueryWrapper<AdUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AdUser::getName, dto.getName());

        AdUser user = getOne(queryWrapper, true);
        if (user == null) {
            return notExits;
        }
        String s = DigestUtils.md5DigestAsHex((dto.getPassword() + user.getSalt()).getBytes());
        if (s.equals(user.getPassword())){
            user.setPassword("");
            user.setSalt("");
            String token = AppJwtUtil.getToken(user.getId().longValue());
            HashMap<String, Object> map = new HashMap<>();
            map.put("token",token);
            map.put("user",user);
            return ResponseResult.okResult(map);
        }else {
            return pwdError;
        }

    }

//    public static void main(String[] args) {
//        String s = DigestUtils.md5DigestAsHex((123456+"123456").getBytes());
//        System.out.println(s);
//    }
}
